<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <p-spin :spinning="spinning">
      <TaskTitle :title-name="titleName" icon-name="to do" color="blue" />
      <div class="g-drawer-list-container">
        <div class="g-drawer-progress-container">
          <TitleSecondary title="审批流程图" />
          <ProgressStaus />
        </div>
        <ProgressGraph :data="detail.nodeFlowChartList" />
        <TitleSecondary title="基本信息" />
        <FormBasicInfo :is-edit="false" :form="form" :page-type="pageType" />
        <TitleSecondary title="销售责任人" />
        <TableSaleList
          :data-source="detail.mforecastSalesList"
          :page-type="pageType"
          style="margin-bottom: 20px"
        />
        <TitleSecondary title="FCST明细" />
        <p-tabs
          class="g-drawer-poros-tabs"
          :default-active-key="'1'"
          type="card"
          @change="handleTabChange"
        >
          <p-tab-pane key="1" :tab="'FCST'">
            <TablePlanDetail
              :is-edit="hasEdit"
              :buttons="hasEdit ? undefined : []"
              local-key="m3-group-record"
              :has-compare.sync="hasCompare"
              :data-source="planDetailList"
              :plan-sales="detail.mforecastSalesList"
              :plan-id="detail.id"
              :mforecast-sales-id="detail.mforecastSalesId"
              :hide-keys="['selection', 'mforecastSalesId', 'relationId']"
              :page-type="pageType"
              :time-range="timeRange"
              :parent-id="form.salesOrganization"
              :default-show="[]"
              :default-fixed="[]"
            />
          </p-tab-pane>
          <p-tab-pane key="2">
            <span slot="tab">总览</span>
            <TablePlanDetailTotal
              :data-source="totalDetailList"
              :plan-sales="detail.mforecastSalesList"
              :plan-id="planId"
              :plan-type="planType"
              :hide-keys="['selection']"
              :time-range="[form.startTime, form.endTime]"
              :plan-sales-id="detail.planSalesId"
              local-key="m3-group-record-total"
            />
          </p-tab-pane>
        </p-tabs>

        <ProgressLog :list="logList" />
        <BottomLine />
      </div>
      <ButtonGroup
        class="g-drawer-footer"
        :options="filterButtons"
        @click="handleButtonClick"
      />
      <DialogTransfer
        :visible.sync="visibleTransfer"
        :plan-id="planId"
        @change="onClose"
      />
    </p-spin>
  </p-drawer>
</template>

<script>
import FormBasicInfo from './FormBasicInfo.vue';
import TableSaleList from './TableSaleList.vue';
import ProgressGraph from '@/components/task/ProgressGraph.vue';
import ProgressLog from '@/components/task/ProgressLog.vue';
import ProgressStaus from '@/components/task/ProgressStaus.vue';

import { postPlanGroupRecord } from '@/api/forecast';
import TablePlanDetail from './TablePlanDetail.vue';
import TablePlanDetailTotal from './TablePlanDetailTotal.vue';
import DialogTransfer from '@/components/dialog/DialogTransferForecast.vue';

import { isEmpty } from '@/utils/is';
import DrawerMixin from './mixin';

const requireKey = [
  'customerCode',
  'modelName',
  'modelNumber',
  'application',
  'appearance',
  'modelCutRate',
  'factoryCode',
  'fcst',
];

export default {
  components: {
    FormBasicInfo,
    TablePlanDetail,
    TablePlanDetailTotal,
    TableSaleList,
    ProgressGraph,
    ProgressLog,
    ProgressStaus,
    DialogTransfer,
  },

  mixins: [DrawerMixin],

  data() {
    return {
      planDetailList: [],
      visibleTransfer: false,
      hasCompare: false,
    };
  },
  computed: {
    footerButtons() {
      return [
        {
          key: 'submit',
          type: 'primary',
          label: '提交',
          auth: true,
        },
        {
          key: 'save',
          label: '保存',
          auth: true,
        },
        {
          key: 'transfer',
          label: '转他人处理',
          auth: true,
        },
        {
          key: 'close',
          label: '返回',
        },
      ];
    },
  },

  methods: {
    onClose() {
      this.hasCompare = false;
      this.$emit('update:visible', false);
      this.$emit('fresh');
    },
    async submitData(operating) {
      const startPlanDetailList = this.planDetailList.map((item) => {
        return {
          m9RelationId: item.m9RelationId,
          relationId: item.relationId,
          factoryCode: item.factoryCode,
          category: item.category,
          appearance: item.appearance,
          application: item.application,
          customerCode: item.customerCode?.key,
          customerName: item.customerCode?.label,
          innerItem: item.innerItem,
          item: item.item,
          manufactureArea: item.manufactureArea,
          modelCutRate: item.modelCutRate,
          modelCode: item.modelName?.key,
          modelName: item.modelName?.label,
          modelNumber: item.modelNumber?.key,
          modelInfoName: item.modelNumber?.label,
          mforecastSalesId: item.mforecastSalesId,
          remark: item.remark,
          price: JSON.stringify(item.price),
          fcst: JSON.stringify(item.fcst),
          lastFcst: JSON.stringify(item.lastFcst),
          changeRemark: item.changeRemark,
        };
      });
      if (operating === 0) {
        const isValid = this.checkData(startPlanDetailList);
        if (!isValid) return new Promise(() => {});
        return await postPlanGroupRecord({
          id: this.planId,
          operating,

          fcstDetailList: startPlanDetailList,
        });
      } else {
        return await postPlanGroupRecord({
          id: this.planId,
          operating,
          fcstDetailList: startPlanDetailList,
        });
      }
    },
    checkData(list) {
      console.log('list: ', list);
      if (!list.length) {
        this.$message.error('请先填写表格内容！');
        return false;
      }
      if (!this.hasCompare) {
        this.$message.error('请先进行版本差异对比！');
        return false;
      }
      const isChangeRemark = list.every((item) => {
        const fcst = JSON.parse(item.fcst);
        const lastFcst = JSON.parse(item.lastFcst);

        const isSame = Object.keys(lastFcst).every((item) => {
          const last = JSON.stringify(lastFcst[item]);
          const current = JSON.stringify(fcst[item]);
          return last === current;
        });

        if (isSame) return true;
        return !isEmpty(item.changeRemark);
      });
      if (!isChangeRemark) {
        this.$message.error('请填写需求变更说明！');
        return false;
      }
      const index = list.findIndex((item) => {
        // const price = JSON.parse(item.price);
        // const isPrice = Object.keys(price).some((key) => isEmpty(price[key]));
        const fcst = JSON.parse(item.fcst || '{}');

        const values = Object.keys(fcst).reduce((pre, cur) => {
          const value = Object.keys(fcst[cur]).map((key) => fcst[cur][key]);
          pre.push(...value);
          return pre;
        }, []);
        const isFcst = values.some((key) => isEmpty(key));
        return isFcst || requireKey.some((key) => isEmpty(item[key]));
      });
      if (index > -1) {
        this.$message.error('计划明细表数据未填写完整，请补充！');
        return false;
      }
      return true;
    },
    closeCallback() {
      this.onClose();
    },
    async submitCallback() {
      await this.submitData(0);
      this.$message.success('提交成功！');
      this.closeCallback();
    },
    async saveCallback() {
      await this.submitData(1);
      this.$message.success('保存成功！');
      this.closeCallback();
    },
    transferCallback() {
      this.visibleTransfer = true;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
  },
};
</script>
